from utils.common.db_handle import route_del
from utils.common.request_handle import RouteSend


def get_mac_status(mac_hmac_dict: dict, user: object):
    """
    循环获取路由器的状态信息
    :param mac_hmac_dict: {'00156C000006': 'oDgTOsbHxwyBCdzO4itzvjNJWwI=', '00156C000008': 'AmkjCDT5b8bYZz1OajAEOP8H/5U='}
    :param user: 用户对象
    :return: {'00156C000006': {'00156C000006': '在线', 'ip': '10.144.0.202'}, }
    """
    results = {}
    rs = RouteSend()  # 实例化发送请求的类

    for k, v in mac_hmac_dict.items():
        check_mac_result = rs.check_mac(user, k, v)  # 检查 Mac
        if check_mac_result:
            # 若路由器复位状态，回收 tos，更新数据库
            if check_mac_result.get('data').get('enabled') == 0:
                route_del(k)

            if check_mac_result.get("data").get("connection") == "disconnected":
                results.update(
                    **{k: {'status': '离线', 'ip': '', 'enabled': check_mac_result.get('data').get('enabled', 1)}})
            else:
                results.update(**{k: {'status': '在线', 'ip': check_mac_result.get('data').get('address'),
                                      'enabled': check_mac_result.get('data').get('enabled', 1)}})

    return results


def change_route_status(data, mac_status):
    """
    改变路由器状态
    :param data: [{"name": "1586515834", "mac": "00156C000006", "status": "在线", "server": "raccess1.vpn.cn", "tunnel":
    "通道1", "bind_time": "2020-04-16 16:39:47"}]
    :param mac_status: {'00156C000006': {'status': '在线', 'ip': '10.144.0.202'}, }
    :return:
    """

    for i in data:
        mac_addr = i.get('mac')
        i.update(mac_status.get(mac_addr))

    return data


def transform_date(date_list):
    """
    转换统计页面，用户列表、路有设备数目，每日数目
    :param date_list: <QuerySet [{'year': 2020, 'month': 1, 'day': 11 'n': 1}, {'year': 2020, 'month': 2, 'day': 12, 'n': 1}]>
    :return: [{'date': '2020-1-11', 'nums': 1}, {'date': '2020-2-12', 'nums': 1}]
    """
    date_nums_list = []

    for item in date_list:
        date_nums_list.append({
            'date': '{}-{}-{}'.format(item.get('year'), item.get('month'), item.get('day')),
            'nums': item.get('n')
        })

    return date_nums_list

